package com.shasselclub.api.v1.service.impl;
import cn.emay.util.SendMessageUtils;
import com.shasselclub.api.v1.contants.CodeMessageConstant;
import com.shasselclub.api.v1.contants.RedisConstants;
import com.shasselclub.api.v1.service.GetCodeService;
import com.shasselclub.api.v1.service.RedisService;
import com.shasselclub.api.v1.service.ValidMobileAndCodeService;
import com.shasselclub.api.v1.valid.MobileForm;
import com.shasselclub.common.constant.ResultModel;
import com.shasselclub.common.constant.ResultStatus;
import com.shasselclub.common.utils.DateUtil;
import com.shasselclub.common.utils.IpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.validation.BindingResult;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.concurrent.TimeUnit;

/**
 * @program: zntg_v1
 * @description:
 * @author: zhengyunfei
 * @create: 2018-10-30 15:48
 **/
@Service("getCodeService")
public class GetCodeServiceImpl implements GetCodeService {
    @Autowired
    private ValidMobileAndCodeService validMobileAndCodeService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private Environment env;

    public boolean getCode(@Valid MobileForm loginRequest, BindingResult bindingResult, HttpServletRequest request, ResultModel resultModel) {
        try{
            String mobile=loginRequest.getMobile();//手机号
            if(bindingResult.hasErrors()){
                if (validMobileAndCodeService.ValidMobile(bindingResult, resultModel)){
                    return true;
                }
            }else{
                //参数校验成功
                String vcode=  RandomStringUtils.randomNumeric(6);
                String key=mobile+vcode;
                String today= DateUtil.getToDay(DateUtil.YYYMMMDD);
                String sendCountKey="getCodeCountToday"+mobile+today;
                int sendCount=0;
                if(redisService.exists(sendCountKey)){
                    sendCount=Integer.parseInt(redisService.get(sendCountKey)+"");
                }
                if(sendCount>5){
                    resultModel.setCode(ResultStatus.AUTH_ERROR_24.getCode());
                    resultModel.setMessage(ResultStatus.AUTH_ERROR_24.getMessage());
                    return true;
                }
                //存放该手机号码今天发送短信的次数到缓存中
                redisService.set(sendCountKey,sendCount++);
                String ip= IpUtils.getIp(request);
                String ipSendCountKey="getCodeCountIpToday"+mobile+ip;
                int ipSendCount=0;
                if(redisService.exists(ipSendCountKey)){
                    ipSendCount=Integer.parseInt(redisService.get(ipSendCountKey)+"");
                }
                if(ipSendCount>10){
                    resultModel.setCode(ResultStatus.AUTH_ERROR_24.getCode());
                    resultModel.setMessage(ResultStatus.AUTH_ERROR_24.getMessage());
                }
                //将短信验证码保存到缓存中，并设置1分钟有效期
                redisService.set(key,vcode, RedisConstants.CODE_EXPIRES_MINUTES, TimeUnit.MINUTES);
                resultModel.setCode(ResultStatus.CODE_SEND_SUCCESS.getCode());
                resultModel.setMessage(ResultStatus.CODE_SEND_SUCCESS.getMessage());
                //发送短信
                //获取短信签名
                String signature=env.getProperty(CodeMessageConstant.SMS_SIGNATURE);
                String codeTemplate=env.getProperty(CodeMessageConstant.SMS_CODE_TEMPLATE);
                SendMessageUtils.setSingleSms(signature+codeTemplate.replace(CodeMessageConstant.XX,vcode),mobile,false);
                resultModel.setCode(ResultStatus.CODE_SEND_SUCCESS.getCode());
                resultModel.setMessage(ResultStatus.CODE_SEND_SUCCESS.getMessage());

            }
        }catch (Exception e){
            e.printStackTrace();
            resultModel.setCode(ResultStatus.ERROR.getCode());
            resultModel.setMessage(ResultStatus.ERROR.getMessage());
        }
        return false;
    }
    /**
     * 校验短信验证码
     */
    public boolean validCode(String mobile,String vcode,ResultModel resultModel){
        //参数校验成功
        boolean codeSuccess=false;
        //校验验证码是否正确
        String key=mobile+vcode;
        String mobileCodeCommonKey="mobile_code_common";
        String codeCommon=CodeMessageConstant.MOBILE_CODE_COMMON;
        if(redisService.exists(mobileCodeCommonKey)){
            codeCommon=redisService.get(mobileCodeCommonKey).toString();
        }
        if(vcode.equals(codeCommon)){
            codeSuccess=true;
        }
        if(redisService.exists(key)||codeSuccess) {
            //验证码校验正确
            codeSuccess=true;
        }else{
            resultModel.setMessage(ResultStatus.CODE_ERROR.getMessage());
            resultModel.setCode(ResultStatus.CODE_ERROR.getCode());
            codeSuccess=false;
        }
        return codeSuccess;
    }
}
